<?php
/**
 * Created by PhpStorm.
 * User: minicart
 * Date: 2018/9/26
 * Time: 21:01
 */

namespace app\models;

use think\Model;

/**
 * Class AuthGroupAccessModel
 * @package app\models
 */
class AuthGroupAccessModel extends Model
{
    protected $table = 'edu_auth_group_access';

    /**
     * @param $id
     * @param string $type
     * @return AuthGroupAccessModel|array|null
     * @throws \think\exception\DbException
     */
    public static function getById($id,$type = 'all')
    {
        if(!is_numeric($id)) {
            return [];
        }
        $auth_group_access = self::get(['uid'=>$id]);
        if($auth_group_access) {
            return (isset($auth_group_access[$type])) ?  $auth_group_access[$type] : $auth_group_access;
        }
        return [];
    }

    /**
     * 获取用户所有权限
     * @param $uid
     * @param int $type
     * @return array|false|\multitype|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserRules($uid, $type = 1)
    {
        $where = array(
            'uid' => $uid,
        );
        $menuModel = new MenuModel();
        $group_id = $this->where($where)->value('group_id');
        $group_id = explode(',', $group_id);
        $ruleStr = '';
        foreach ($group_id as &$value) {
            $rules = AuthModel::where('id', $value)->value('rules');
            $ruleStr .= ',' . $rules;
        }
        $ruleArr = explode(',', $ruleStr);
        unset($ruleArr[0]);
        if (!$ruleArr) {
            return array();
        }
        $rules_arr = array_unique($ruleArr);
        if ($group_id == config('administrator')) {
            $menus = $menuModel->getMenus('', $type);
        } else {
            $menus = $menuModel->getMenus($rules_arr, $type);
        }
        $menus = get_column($menus, 2);
        return $menus;
    }
}